#!/usr/bin/perl -w
#
# @param $1 install home
# @param $2 delimiter
# @param $3 host
# @param $4 port
# @param $5 username
# @param $6 password
#
# -- 05/27/2009 Created by Zhixin Li
# -- Used to collect mysql table status
#
# -- check if row,data_length and index_length column include non-digit value,  07/10/2009  Zhixin Li
use strict;

my ($MYSQL_HOME,$DELIM,$HOST,$PORT,$USER,$PASS) = @ARGV;
my $PARAM="";
$PARAM="$PARAM -h\"$HOST\"" if (defined($HOST) && $HOST ne "");
$PARAM="$PARAM -P\"$PORT\"" if (defined($PORT) && $PORT ne "");
$PARAM="$PARAM -u\"$USER\"" if (defined($USER) && $USER ne "");
$PARAM="$PARAM -p\"$PASS\"" if (defined($PASS) && $PASS ne "");

my $MYSQL="$MYSQL_HOME/bin/mysql";
my $MYSQLADMIN="$MYSQL_HOME/bin/mysqladmin"; 

if ($^O =~ m/MSWin32/) {
  $MYSQL =~ s/\//\\/g;
  $MYSQLADMIN =~ s/\//\\/g;
}
# Check if mysqld is alive
my $retmsg=`$MYSQLADMIN $PARAM ping 2>&1`;
chomp($retmsg);
if ( "$retmsg" ne "mysqld is alive" ) {
    print "em_error=Status${DELIM}Down\n";
    exit 1;
}
my $SQL3="show variables like 'version'";
my $outvers=`$MYSQL -N -s $PARAM --batch -e "$SQL3"`;
my $vers = substr($outvers,index($outvers,"\t")+1,1);
#print "$vers\n";

my $SQL1="show databases;";
my @listdb=`$MYSQL -N -s $PARAM --batch -e "$SQL1"`;
if ($vers < 5) {
   for (@listdb) {
       chomp($_);
       if ($_ ne "information_schema") {
           my $SQL2 = "show table status from $_";
           my @tableinfo = `$MYSQL -N -s $PARAM --batch -e "$SQL2"`;
           foreach my $line (@tableinfo) {
               chomp($line);
               my @row = split(/\t/,$line);
               my $grep = grep(/\D/,$row[3]); 
               if ( $grep == 1) {
                    $row[3] = 0;
               }
               $grep = grep(/\D/,$row[5]); 
               if ( $grep == 1) {
                    $row[5] = 0;
               }
               $grep = grep(/\D/,$row[7]); 
               if ( $grep == 1) {
                    $row[7] = 0;
               }
               print "em_result=$_|$row[0]|$row[1]|$row[3]|$row[5]|$row[7]\n";
           }
        } 
   }
} else {
   for (@listdb) {
       chomp($_);
       if ($_ ne "information_schema") {
           my $SQL2 = "show table status from $_";
           my @tableinfo = `$MYSQL -N -s $PARAM --batch -e "$SQL2"`;
           foreach my $line (@tableinfo) {
               chomp($line);
               my @row = split(/\t/,$line);
               my $grep = grep(/\D/,$row[4]);
               if ( $grep == 1) {
                    $row[4] = 0;
               }
               $grep = grep(/\D/,$row[6]);
               if ( $grep == 1) {
                    $row[6] = 0;
               }
               $grep = grep(/\D/,$row[8]);
               if ( $grep == 1) {
                    $row[8] = 0;
               }
               print "em_result=$_|$row[0]|$row[1]|$row[4]|$row[6]|$row[8]\n";
           }
        }
   }
}
exit 0;

